class PlannedCoursesController < ApplicationController

    before_filter :get_plan
    # user must own plan to create or destroy a planned_course
    before_filter :ownership_required 

    def create
        @planned_course = @plan.planned_courses.build(params[:planned_course])
        if @planned_course.save
            flash[:notice] = "Course added successfully"
            redirect_to(@plan)
        elsif @plan
            flash[:error] = "Course could not be added"
            redirect_to(@plan)
        else
            flash[:error] = "Course could not be added"
            redirect_to(plans_url)
        end

    end

    def destroy
        @planned_course = PlannedCourse.find(:conditions => ["plan_id = ? AND course_id = ?", params[:plan_id], params[:course_id]])
        @planned_course.destroy
        redirect_to(@plan)
    end


    private

        def get_plan
            @plan = Plan.find(params[:planned_course][:plan_id])
        end

        def ownership_required
            if current_user.role == "administrator"
                return true
            elsif current_student.id != @plan.student_id
                redirect_to(PermissionDeniedURL)
            else
                return true
            end
        end


end
